# @Project: diablo
# @File: stock_offline
# @Time: 2023/10/25 11:38
# @User: Jolly
# @Email: jolly@007vin.com

"""
给库存进行批量下架
"""

import datetime

# 定价来源：客户提供的excel

import time
import threading
from queue import Queue

from io import BytesIO
from openpyxl import load_workbook
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure


class BatchStockOffline:

    def __init__(self, merchant_id, file_path):

        self.merchant_id = merchant_id
        self.file_path = f"./{file_path}.xlsx"

        start_time = time.time()

        # 初始化数据库连接
        # 2.0生产库
        self.diablo_conn_2_0 = self.get_mongo_connection("root", "aa123456", "192.168.191.175", "27017")

        # 执行任务
        self.task()

        print("========= 数据插入,共耗时:{}'s =========".format(round(time.time() - start_time, 3)))

    def get_mongo_connection(self, username, password, host, port):
        try:
            # 创建 MongoClient
            client = MongoClient(f"mongodb://{username}:{password}@{host}:{port}",
                                 maxPoolSize=150,
                                 minPoolSize=1,
                                 maxIdleTimeMS=30000,
                                 waitQueueTimeoutMS=2000)

            # 检测连接是否可用，如果连接不可用则抛出异常
            if not client:
                raise ConnectionFailure("从MongoDB连接池中获取连接失败！")

            return client

        except ConnectionFailure as e:
            # 处理连接失败的异常
            print(f"连接MongoDB失败: {e}")
            return None

    # 判断定价协议表是否已有对应数据，有的话就删除
    def check_identify_exist(self, identify):

        check = False

        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["inventory_data"]
                conn = db["ChangYuan_meta_stocks"]

                filter_dict = {
                    "identify": identify,
                    "erp_uid": {"$in": ["T0000002_4TH0WP2OQ_T", "T0000002_4TH0WP2OQ_Z1"]}
                }
                docs_count = conn.count_documents(filter_dict)

                if docs_count > 0:
                    check = True

        except Exception as e:
            print("获取库存存在检测失败 - mongo：", e)
        finally:
            # 将连接放回连接池
            connection.close()

        return check

    # 写入数据
    def update_data(self, *args):

        identify = args[0]

        # 通过oe号和原始品质查找库存记录，可能有多个
        check = self.check_identify_exist(identify)

        if not check:
            with open("./not_hit.txt", "a") as file:
                file.write(identify + "\n")

            return

        # 更新改库存为下架
        filter_dict = {
            "identify": identify
        }

        update_dict = {
            "status": 1
        }

        # 获取2.0MongoDB连接
        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["inventory_data"]
                conn = db["ChangYuan_meta_stocks"]
                conn.update_one(filter=filter_dict, update={'$set': update_dict})

        except Exception as e:
            print("更新2.0MongoDB数据库库存失败：", e)
        finally:
            # 将连接放回连接池
            connection.close()

    # 获取excel数据，生成器返回
    def get_excel_data(self):

        with open(self.file_path, "rb") as file:
            content = file.read()

        # 将内容转换为BytesIO对象
        bytesIO = BytesIO(content)

        # 加载工作簿
        book = load_workbook(bytesIO, read_only=True)

        # 获取活动工作表
        sheet = book.active

        previous = next(sheet.iter_rows(), None)
        for row in sheet.iter_rows():
            yield previous, False
            previous = row
        yield previous, True

    def get_all_excel_data(self):
        """
        获取全部excel
        """

        with open(self.file_path, "rb") as file:
            content = file.read()

        # 将内容转换为BytesIO对象
        bytesIO = BytesIO(content)

        # 加载工作簿
        book = load_workbook(bytesIO, read_only=True)

        # 获取活动工作表
        sheet = book.active

        return sheet.iter_rows()

    # 任务执行
    def task(self):
        q = Queue(maxsize=100)  # 设定最大队列数和线程数

        count = 1

        all_data = self.get_all_excel_data()

        for row in all_data:
            identify = str(row[0].value)

            t = threading.Thread(target=self.update_data, args=(identify, ))
            q.put(t)
            if q.full() == True:
                thread_list = []
                while q.empty() == False:
                    t = q.get()
                    thread_list.append(t)
                    t.start()
                for t in thread_list:
                    t.join()

            print("当前写入数：", count, " 唯一编码为：", identify)

            count += 1

        # 处理残余队列数据
        thread_list = []
        while q.empty() == False:
            t = q.get()
            thread_list.append(t)
            t.start()
        for t in thread_list:
            t.join()


if __name__ == "__main__":
    # file_list = ["hongdexiajia2023102501", "hongdexiajia2023102502", "hongdexiajia2023102601"]
    #
    # for file_path in file_list:
    #     print(f"当前刷写的是-------------------{file_path}----------------------------")
    #     InitAgreementPrice(3, file_path)

    BatchStockOffline(3, "hongdeshangjia20231123")

